#include <bits/stdc++.h>

using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        ListNode *dummyHead = new ListNode(-1);
        dummyHead->next = head;
        ListNode *pre = dummyHead;
        ListNode *cur = head;
        while (cur)
        {
            ListNode *next = cur->next;
            if (cur->val == val)
            {
                pre->next = next;
                cur = next;
            }
            else 
            {
                pre = cur;
                cur = next;
            }
        }
        return dummyHead->next;
    }
};